package com.controller;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.beans.ClassInfo;
import com.beans.StudentInfo;
import com.dao.ClassDao;
import com.dao.StudentDao;
import com.utils.StrUtil;

@Controller @RequestMapping("/student")
public class StudentController {
	@Resource
	StudentDao studentDao;
	@Resource
	ClassDao classDao;
	@RequestMapping("/gotoAddPage")
	public String goAdd(ModelMap map) {
		List<ClassInfo> classList= classDao.findAll(Sort.by(Direction.DESC,"id"));
		map.put("classList",classList);
		return "/admin/student/student_add.jsp";
	}
	@RequestMapping("/add")
	public String addStudent(@ModelAttribute ("stu")StudentInfo stu,ModelMap map) {
		System.out.println(stu);
		
		 List<StudentInfo> studentList=studentDao.findBy身份证号(stu.get身份证号());
		 if(studentList.size()>0) {
			 map.put("msg","身份证号重复"); 
			
			 } 
		 else { studentDao.save(stu);
		 		map.put("msg","添加成功");
		 	 
		 	  }
		 	List<ClassInfo> classList= classDao.findAll(Sort.by(Direction.DESC,"id"));
			map.put("classList",classList);
			return "/admin/student/student_add.jsp";
	}
	@RequestMapping("/search")
	@SuppressWarnings("serial")
	public String search(ModelMap map, String 姓名, String 学员编号, String 班级, String 咨询, String 身份证号, String 进班时间开始,
			String 进班时间结束, String 毕业时间开始, String 毕业时间结束) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy/mm/dd");
		//多条件查询
		Specification<StudentInfo> spec = new Specification<StudentInfo>() {
			public Predicate toPredicate(Root<StudentInfo> root, CriteriaQuery<?> query, CriteriaBuilder c) {
				List<Predicate> list = new ArrayList<>();

				if (!StrUtil.isNullOrEmpty(姓名)) {
					list.add(c.like(root.get("姓名").as(String.class), "%" + 姓名.trim() + "%"));
				}

				if (!StrUtil.isNullOrEmpty(学员编号)) {
					list.add(c.like(root.get("学员编号").as(String.class), "%" + 学员编号.trim() + "%"));
				}

				if (!StrUtil.isNullOrEmpty(班级)) {
					list.add(c.like(root.get("班级"), "%" + 班级.trim() + "%"));
				}

				if (!StrUtil.isNullOrEmpty(咨询)) {
					list.add(c.like(root.get("咨询"), "%" + 咨询.trim() + "%"));
				}

				if (!StrUtil.isNullOrEmpty(身份证号)) {
					list.add(c.like(root.get("身份证号"), "%" + 身份证号.trim() + "%"));
				}

				if (!StrUtil.isNullOrEmpty(进班时间开始)) {
					Date d进班时间开始 = null;
					try {
						d进班时间开始 = df.parse(进班时间开始);
					} catch (ParseException e) {
						e.printStackTrace();
					}
					list.add(c.greaterThanOrEqualTo(root.<Date>get("进班时间"), d进班时间开始));
				}

				/*
				 * if (!StrUtil.isNullOrEmpty(进班时间结束)) { Date d进班时间结束=null; try { d进班时间结束 =
				 * df.parse(进班时间结束); } catch (ParseException e) { e.printStackTrace(); }
				 * list.add(c.lessThanOrEqualTo(root.<Date>get("进班时间"),d进班时间结束)); }
				 * 
				 * if (!StrUtil.isNullOrEmpty(毕业时间开始)) { Date d毕业时间开始=null; try { d毕业时间开始 =
				 * df.parse(毕业时间开始); } catch (ParseException e) { e.printStackTrace(); }
				 * list.add(c.greaterThanOrEqualTo(root.<Date>get("毕业时间"),d毕业时间开始)); }
				 * 
				 * if (!StrUtil.isNullOrEmpty(毕业时间结束)) { Date d毕业时间结束=null; try { d毕业时间结束 =
				 * df.parse(毕业时间结束); } catch (ParseException e) { e.printStackTrace(); }
				 * list.add(c.lessThanOrEqualTo(root.<Date>get("毕业时间"), d毕业时间结束)); }
				 */

				// 此时条件之间是没有任何关系的。
				Predicate[] arr = new Predicate[list.size()];
				return c.and(list.toArray(arr));
			}
		};

		Sort s = Sort.by(Sort.Direction.DESC, "id");
		List<StudentInfo> studentList = this.studentDao.findAll(spec, s);
		map.put("studentList", studentList);
		return "/admin/student/student_manager.jsp";
	}
	@RequestMapping("delete/{studentId}")
	public String deleteStudentById(@PathVariable("studentId")Integer studentId,ModelMap map) {
		studentDao.deleteById(studentId);
		map.put("studentList",studentDao.findAll());
		map.put("msg","删除成功");
		return "/admin/student/student_manager.jsp";
	}
	@RequestMapping("update/{studentId}")
	public String goUpdateStudentById(@PathVariable("studentId")Integer studentId,ModelMap map) {
		map.put("stu",studentDao.findById(studentId).get());
		List<ClassInfo> classList = classDao.findAll(Sort.by(Direction.DESC, "id"));
		map.put("classList", classList);
		return "/admin/student/student_update.jsp";
	}
	@RequestMapping("update")
	public String updateStudent(@ModelAttribute ("stu")StudentInfo stu,ModelMap map) {
		System.out.println(stu);
		// 这两句代码的意思,是不要更照片(防止把原来有的照片更新没了)照片不能改变
		StudentInfo oldStudent = studentDao.getOne(stu.getId());
		stu.set照片(oldStudent.get照片());
		studentDao.save(stu);
		List<ClassInfo> classList = classDao.findAll(Sort.by(Direction.DESC, "id"));
		map.put("classList", classList);
		map.put("msg","修改成功");
		return "/admin/student/student_update.jsp";
	}
	@PostMapping("/addWord")
	public String addWord(StudentInfo stu, ModelMap m, MultipartFile picture, Integer x, Integer y, Integer h, Integer w)
			throws IOException {
		//String result=StrUtil.verifyIdCard(stu.get身份证号());
		String result="";
		if(!StrUtil.isNullOrEmpty(result)) {
			m.put("msg", "身份证号校验失败 :  "  +result);
		}
		else {
			List<StudentInfo> oldStuList=studentDao.findBy身份证号(stu.get身份证号());
			if(oldStuList.size()>0) {
				m.put("msg", "身份证号" +stu.get身份证号()  +" 已经录入,   不能重复录入 ! ,");
			}
			else {
				if(!picture.isEmpty()) {
					byte[] imgByte = picture.getBytes();
					ByteArrayInputStream bis = new ByteArrayInputStream(imgByte); // 将byte数组转换为image对象 BufferedImage
					BufferedImage bufferedImage = ImageIO.read(bis); // 获得当前的图片的高度和宽度 int
					int thisHeight = bufferedImage.getHeight();
					int thisWidth = bufferedImage.getWidth(); // 获得裁剪的图片的高度和宽度 x y为裁剪的其实位置 w h 为裁剪的图片大小
					BufferedImage subImage = bufferedImage.getSubimage(Integer.valueOf(x), Integer.valueOf(y), Integer.valueOf(w),
							Integer.valueOf(h)); // 判断是否等于原图的大
			//		  if(subImage.getWidth()>=0 || subImage.getHeight()>=0){ //设置绘制的图片的大小
					BufferedImage tempImg = new BufferedImage(Integer.valueOf(w), Integer.valueOf(h), BufferedImage.TYPE_INT_RGB); // 绘制图片
					tempImg.getGraphics().drawImage(subImage.getScaledInstance(w, h, Image.SCALE_DEFAULT), 0, 0, null); // 创建字节输入流
					ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
					ImageIO.write(tempImg, "JPEG", byteArrayOutputStream); // 获取新图片的数组 byte[]
			
					byte[] newImg = byteArrayOutputStream.toByteArray();
					stu.set照片(newImg);
				// }
		
				}		
				studentDao.save(stu);
				m.put("msg", "信息添加成功!");
			}
		}

		m.put("stu", stu);
		return "/admin/student/student_add_word.jsp";
	}
	@RequestMapping("/photo")
	public void getPic(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		if(StrUtil.isNullOrEmpty(id)) {
			return ;
		}
		StudentInfo stu = studentDao.getOne(Integer.parseInt(id));
		response.setContentType("image/jpg");
		ServletOutputStream outptuStream = response.getOutputStream();
		if(stu.get照片()!=null) {
			outptuStream.write(stu.get照片());
		}
		else {
			return;
		}
	}
}
